import iButton from '@/components/carGoods/i-button.vue'
import carInfoHeader from '@/components/afterSales/carInfoHeader.vue'
import addGoodsPopup from './components/addGoods-popup.vue'
import editServePopup from './components/edit-serve-popup.vue'
import installModePopup from './components/install-mode-popup.vue'

// 左滑操作组件
import uniSwipeAction from '@/components/uni-swipe-action/uni-swipe-action.vue'
import uniSwipeActionItem from '@/components/uni-swipe-action-item/uni-swipe-action-item.vue'

// 生成二维码插件
import tkiQrcode from '@/components/tki-qrcode/tki-qrcode.vue'

export default {
  components: {
    iButton,
    carInfoHeader,
    addGoodsPopup,
    editServePopup,
    installModePopup,
    tkiQrcode, // 生成二维码插件
    uniSwipeAction,
    uniSwipeActionItem,
  },

  data() {
    return {
      payShow: true,
      intervalwx: null,
      id: 1,
      isSubmit: false, // 是否已提交
      // 实物产品列表
      productList: [],

      // 施工服务列表
      serveList: [],

      errList: [], // 异常项列表
      installMode: {
        id: 0,
        name: '到店安装',
      }, // 安装方式的值

      goodsShow: false, // 显示添加商品弹框
      serveShow: false, // 显示编辑服务弹框
      installModeShow: false, // 显示安装方式弹框
      // 金额价格部分
      priceDataCont: {
        goodsPrice: 0.0,
        servePrice: 0.0,
        totalPrice: 0.0,
      },
      // 确认信息
      confirmInfo: {
        guideName: '', // 导购员确认
        userDate: '',
        userName: '', // 客户签名确认
        orderNo: '', // 订单号
      },
      couponAllMoney: 0, // 优惠总金额
      otherCoupons: null, //代金券
      coupons: [], // 优惠卡券
      isSelectedCoupons: 0, // 是否选择了优惠卡券 0 未选择 1 优惠券 2 福利包
      hasCoupon: false, // 客户是否含有优惠卡券

      remark: '', // 备注
      // 支付收款码标题
      tabPayTitleList: [
        {
          name: '支付宝支付',
        },
        {
          name: '微信支付',
        },
        {
          name: '现金支付',
        },
      ],
      payTitleIndex: 0, // 当前收款码
      detailData: {}, // 详情所有的数据
      payqrImg: [], // 生成的支付二维码的图片
      rightOptions: [
        {
          text: '删除',
          style: {
            backgroundColor: '#EB5C02',
          },
        },
      ],

      isRefresh: false, //是否需要刷新订单状态

      freightVal: '', //运费

      billImg: '/static/img/afterSales/piao.png', //收据
      billRemark: '', //收据备注

      qrcode:
        '',
    }
  },

  computed: {
    // 金额价格部分
    priceData: {
      get() {
        // 商品和服务金额
        let obj = {
          goodsPrice: this.sumFn(
            this.productList,
            'productPrice',
            'productCount'
          ),
          servePrice: this.sumFn(
            this.serveList,
            'servicePrice',
            'serviceCount'
          ),
          couponsAllMoney: this.priceDataCont.couponsAllMoney,
        }
        // 合计金额，减去优惠金额
        if (obj.couponsAllMoney > 0) {
          obj.totalPrice = Math.max(
            (
              obj.goodsPrice +
              obj.servePrice -
              obj.couponsAllMoney +
              parseFloat(this.freightVal)
            ).toFixed(2),
            0.0
          )
        } else {
          obj.totalPrice = Math.max(
            (
              obj.goodsPrice +
              obj.servePrice +
              obj.couponsAllMoney +
              parseFloat(this.freightVal | 0)
            ).toFixed(2),
            0.0
          )
        }

        return obj
      },
      set(v) {
        this.priceDataCont = v
      },
    },

    // 显示优惠券
    couponData() {
      // 是否有可用优惠券
      if (this.hasCoupon) {
        // 是否选择了优惠券
        if (this.isSelectedCoupons === 1) {
          return '-￥' + this.priceDataCont.couponsAllMoney
        } else {
          return '选择优惠卡券'
        }
      } else {
        return '无可用优惠卡券'
      }
    },

    // 显示套餐卡
    setMenuData() {
      // 是否有可用套餐卡
      if (this.hasCoupon) {
        // 是否选择了优惠券
        if (this.isSelectedCoupons === 2) {
          // return '-￥' + this.priceDataCont.couponsAllMoney
          return this.coupons
        } else {
          return [{ name: '选择套餐卡' }]
        }
      } else {
        return [{ name: '无可用套餐卡' }]
      }
    },
    //是否显示用户确认
    isShowSign() {
      if (
        this.detailData.statusStr === '待提交' ||
        this.detailData.statusStr === '待确认'
      ) {
        return true
      }

      if (!this.confirmInfo.userName) {
        return false
      }

      return true
    },
  },

  filters: {
    // 过滤订单状态显示文字
    handleStatus(val) {
      let status = {
        0: '待提交',
        1: '待付款',
        2: '待施工',
      }
      return status[val]
    },

    // 处理金额数字小数点精度
    handleNumFloat(val) {
      return parseFloat(val)
    },
  },

  onLoad(e) {
    this.id = e.id
    if (e.isSubmit) {
      this.isSubmit = parseInt(e.isSubmit) !== 1
      uni.setNavigationBarTitle({
        title: '报价单-已生成订单',
      })
    } else {
      this.isSubmit = false
    }
    this.confirmInfo.guideName = this.$store.state.userInfoDetail.user.userName
    uni.$on('userConfirm', date => {
      this.confirmInfo.userName = date.userName
    })

    // 选择了优惠券，处理优惠券到对应的商品或服务里
    // 回调参数data：优惠金额相关数据，coupon：选择的优惠券
    uni.$on('couponChange', data => {
      this.otherCoupons = null
      this.coupons = []
      if (data.type === 1) {
        //选择优惠券
        // 产品列表 添加优惠券
        this.productList.map(item => {
          item.couponId = data.coupon.coupon_Id
          item.coupon_Details_Id = data.coupon.coupon_Details_Id
          item.couponMoney = data.discountTotalAmount
        })

        // 服务列表 添加优惠券
        this.serveList.map(item => {
          item.couponId = data.coupon.coupon_Id
          item.coupon_Details_Id = data.coupon.coupon_Details_Id
          item.couponMoney = data.discountTotalAmount
        })
      } else {
        //选择福利包
        this.productList.map(product => {
          let index = data.coupon.findIndex(
            item => product.productId === item.goods_Service_Type_Id
          )
          if (index === -1) {
            product.couponId = ''
            product.coupon_Details_Id = ''
            product.couponMoney = 0
            product.actuallyAmount = 0
          } else {
            product.couponId = data.coupon[index].coupon_Id
            product.coupon_Details_Id = data.coupon[index].coupon_Details_Id
            product.couponMoney = data.coupon[index].discountAmount
            product.actuallyAmount = data.coupon[index].actuallyAmount
          }
        })

        this.serveList.map(service => {
          let index = data.coupon.findIndex(
            item => service.serviceId === item.goods_Service_Type_Id
          )
          if (index === -1) {
            service.couponId = ''
            service.coupon_Details_Id = ''
            service.couponMoney = 0
            // service.actuallyAmount = 0
            service.service_Calculate_Rule_id = ''
          } else {
            service.couponId = data.coupon[index].coupon_Id
            service.coupon_Details_Id = data.coupon[index].coupon_Details_Id
            service.couponMoney = data.coupon[index].discountAmount
            // service.actuallyAmount = data.coupon[index].actuallyAmount
            service.service_Calculate_Rule_id =
              data.coupon[index].goods_Calculate_Rule_Id
          }
        })
        data.coupon.map(item => {
          if (item.goodsRuleType === 4) {
            this.otherCoupons = {
              coupon_Id: item.coupon_Id,
              coupon_Details_Id: item.coupon_Details_Id,
            }
          }
        })
        this.coupons = data.coupon
      }

      // 添加优惠金额
      this.priceDataCont.couponsAllMoney = data.discountTotalAmount
      this.couponAllMoney = data.discountTotalAmount
      this.isSelectedCoupons = data.type
    })
    this.getDetailData()
    this.getCouponList()
  },

  onShow() {
    if (this.isRefresh) {
      this.getDetailData()
    }
  },
  onBackPress(){
    clearInterval(this.intervalwx)
    this.intervalwx = null
  },
  onHide() {
    clearInterval(this.intervalwx)
    this.isRefresh = true
  },
  beforeDestroy() {
    uni.$off('couponChange')
  },
  methods: {
    paySuccess(){
      if(this.isSubmit && this.detailData.status===5){
        console.log('true')
			  this.intervalwx = setInterval(() => {
			    setTimeout(() => {
            this.GetArriveQuotationList()
          },0)
			  }, 3000)
      }
    },
    async GetArriveQuotationList() {
		  try {
		    const res = await this.$api.afterSales.GetArriveQuotationList({
		      arriveId: this.$store.state.afterSales.arrvialId,
		    })
		    let info = res.data.find(item => item.quotationId === this.id)
		    console.log(info,'asdsd')
		    if(!info){
          this.payShow = false
		      uni.showToast({
		        title: '支付成功',
		        icon: 'none'
		      })
          clearInterval(this.intervalwx)
		      this.intervalwx = null
		    }
		  } catch (err) {
		    console.log(err)
		  }
    },
    // 获取详情数据
    async getDetailData() {
      uni.showLoading()
      try {
        const res = await this.$api.afterSales.GetQuotationDetail({
          quotationId: this.id,
        })
        if (!this.isRefresh) {
          // 第一次加载页面数据
          this.productList = res.data.products // 产品列表
          this.serveList = res.data.services // 服务列表
          this.errList = res.data.workExceptions // 检测异常项列表
          // 安装方式
          this.installMode = {
            id: res.data.installationMethod,
            name: res.data.installationMethodStr,
          }

          this.freightVal = res.data.freight
          this.remark = res.data.reason

          // 金额价格部分
          this.priceData = {
            goodsPrice: res.data.productsAllMoney,
            servePrice: res.data.servicesAllMoney,
            couponsAllMoney: res.data.couponsAllMoney,
            totalPrice: res.data.allMoney,
          }
        }
        if (res.data.status !== 1) {
          // 更新价格
          this.priceData = {
            goodsPrice: res.data.productsAllMoney,
            servePrice: res.data.servicesAllMoney,
            couponsAllMoney: res.data.couponsAllMoney,
            totalPrice: res.data.allMoney,
          }
          // 更新优惠券
          if (res.data.coupons) {
            this.coupons = []
            res.data.coupons.forEach(item => {
              if (item.is_Package) {
                this.isSelectedCoupons = 2
                this.coupons.push({
                  name: item.couponName,
                  discountAmount: Math.abs(item.couponPrice),
                })
              } else {
                this.isSelectedCoupons = 1
                this.priceDataCont.couponsAllMoney = item.couponPrice
              }
            })
          }
        }

        this.confirmInfo = {
          guideName: res.data.createUserName, // 导购员确认
          userDate: res.data.sureTime,
          userName: res.data.isSure, // 客户签名确认
          orderNo: res.data.notify, // 订单号
        }

        // this.coupons = res.data.coupons

        // 详情状态为待付款，就处理支付链接生成二维码
        if (res.data.status === 5) {
          res.data.aliPayQrImg = JSON.parse(res.data.aliPayQrImg).Data
          res.data.weChatPayQrImg = JSON.parse(res.data.weChatPayQrImg).Data
        }

        this.detailData = res.data
        this.paySuccess()
        if (res.data.status === 5) {
          if (!this.payqrImg.map(p => p.type).includes(this.payTitleIndex)) {
            let s = {
              0: 'aliqrcode',
              1: 'wxqrcode',
            }
            this.$nextTick(() => {
              this.$refs[s[this.payTitleIndex]]._makeCode()
            })
          }
        }
      } catch (err) {
        console.log(err)
      }
      uni.hideLoading()
    },

    // 根据商品匹配相关服务
    async GetServiceFeeByGoods(list) {
      let data = {
        configuration_Id: this.$store.state.afterSales.carInfo.carId,
        // 过滤有服务才传入对应参数
        getServiceFeeGoodsList: list
          .filter(item => !!item.maintenance_Type_Id)
          .map(item => ({
            maintenance_Type_Id: item.maintenance_Type_Id,
            maintenance_Goods_Id: item.id,
            count: item.amount,
          })),
      }
      try {
        const res = await this.$api.afterSales.GetServiceFeeByGoods(data)
        // 添加对应的key名
        let list = res.data.map(item => ({
          ...item,
          couponId: null,
          couponMoney: 0,
          serviceCount: item.serviceNum,
          serviceId: item.maintenance_Type_Id,
          serviceName: item.service_Name,
          servicePrice: item.service_Price,
        }))
        this.serveList = [...this.serveList, ...list]
      } catch (err) {
        console.log(err)
      }
    },

    // 确定添加商品
    addGoodsChange({ type, data }) {
      console.log(data)
      // type为true则是点击确定按钮，false为继续添加商品
      if (type) {
        this.goodsShow = false
        let list = data.map(item => ({
          ...item,
          productCount: item.amount,
          productId: item.id,
          productName: item.goods_Name,
          inPrice: item.in_Price,
          productPrice: item.isVisualGoods ? 0 : item.sale_Price,
          addRange: item.added_Rate,
          goodsTypeId: item.maintenance_Type_Id,
        }))
        this.productList = this.productList.concat(list)
        this.GetServiceFeeByGoods(list)
      } else {
        console.log('继续添加，商品信息', list)
      }
    },

    // 打开服务弹框
    servePopupOpen(item) {
      // 已生成订单状态，就不能打开服务弹框更改了
      if (this.isSubmit) return

      this.serveShow = true
      this.$nextTick(() => {
        this.$refs.serve.loadData(item)
      })
    },

    // 编辑服务确定/取消
    editServeChange({ type, data }) {
      // type为true则是点击确定按钮，false为继续添加商品
      this.serveShow = false
      if (type) {
        console.log('确定，商品信息', data)
      }
    },

    // 减
    less(item) {
      if (item.productCount <= 1) return
      item.productCount -= 1
    },

    // 加
    add(item) {
      item.productCount += 1
    },

    // 左滑删除商品项
    delChange(e) {
      // 需延迟移除数组项
      setTimeout(() => {
        this.productList.splice(e, 1)
      }, 100)
    },

    // 计算商品金额、服务金额的各的总价
    sumFn(list, priceKey, count) {
      let sum = 0
      list.map(item => {
        sum += parseFloat(item[priceKey]) * item[count]
      })
      return sum
    },

    // 预览图片
    previewImg(imgs) {
      uni.previewImage({
        urls: imgs,
        current: 0,
      })
    },

    // 切换支付收款码
    tabPayChange(i) {
      this.payTitleIndex = i
      if (i !== 2) {
        let s = {
          0: 'aliqrcode',
          1: 'wxqrcode',
        }
        this.$nextTick(() => {
          this.$refs[s[this.payTitleIndex]]._makeCode()
        })
      }
    },

    // 删除订单
    delOrder() {
      uni.showModal({
        title: '确认删除该订单？',
        content: '此操作不可撤销',
        confirmColor: '#fbb000',
        success: res => {
          if (res.confirm) {
            this.delOrderApi()
          }
        },
      })
    },
    // 删除订单请求接口方法
    async delOrderApi() {
      uni.showLoading()
      try {
        const res = await this.$api.afterSales.DeleteQuotation({
          quotationId: this.detailData.quotationId,
        })
        uni.showToast({
          title: '已删除',
        })
        let t = setTimeout(() => {
          clearTimeout(t)
          uni.redirectTo({
            url: '/pages_afterSales/newMaintenanceOrder/newMaintenanceOrder',
          })
        }, 1000)
      } catch (e) {
        //TODO handle the exception
      }
      uni.hideLoading()
    },

    // 点击客户签字跳转签字确认页面
    goUserConfirm() {
      if (this.detailData.statusStr === '待确认') {
        this.userConfirm(this.detailData.quotationId)
      }
    },

    // 跳转客户签字确认
    userConfirm(id) {
      let data = JSON.stringify({
        type: 'before',
        count: 2,
      })
      let nId = id ? `&id=${id}` : ''
      uni.navigateTo({
        url:
          '/pages_afterSales/orderConfirm/orderConfirm?typeOptions=' +
          data +
          nId,
      })
    },

    // 二维码事件，储存生成的二维码
    qrResult(data) {
      if (this.payqrImg.length === 2) return false
      this.payqrImg.push({
        type: this.payTitleIndex,
        img: data,
      })
    },

    // 跳转到选择卡券列表页面
    goCouponPage(tab) {
      if (!this.hasCoupon) return
      if (this.detailData.statusStr !== '待提交') return
      if (!this.isSelectedCoupons) {
        //选择优惠券 福利包
        this.$store.commit('afterSales/setOrderGoodsAndService', {
          productList: this.productList.map(item => ({
            maintenance_Type_Id: item.goodsTypeId,
            maintenance_Goods_Id: item.productId,
            sale_Price: item.productPrice,
          })),
          serveList: this.serveList.map(item => ({
            serviceId: item.serviceId,
            service_Calculate_Rule_id: item.service_Calculate_Rule_id,
            sale_Price: item.servicePrice,
          })),
        })
        uni.navigateTo({
          url: '/pages_afterSales/myCoupon/index?status=' + tab,
        })
      }
    },

    cleanCoupon() {
      //清空已选福利包 优惠券
      this.isSelectedCoupons = 0
      this.otherCoupons = null
      this.coupons = []
      //...清空商品服务列表的优惠信息
      this.productList.map(product => {
        product.couponId = ''
        product.coupon_Details_Id = ''
        product.couponMoney = 0
        product.actuallyAmount = 0
      })
      this.serveList.map(service => {
        service.couponId = ''
        service.coupon_Details_Id = ''
        service.couponMoney = 0
        service.service_Calculate_Rule_id = ''
      })
      this.couponAllMoney = 0
      this.priceDataCont.couponsAllMoney = 0
    },

    // 获取优惠券列表数据
    async getCouponList() {
      try {
        const res = await this.$api.afterSales.GetCouponList({
          coupon_class: 0,
          pageIndex: 1,
          pageSize: 10,
          mobile: this.$store.state.afterSales.arrvialPhone,
        })

        // 优惠券列表是否含有卡券
        this.hasCoupon = res.data.list.length !== 0
      } catch (e) {
        console.log(e)
      }
    },

    // 提交
    async submit() {
      uni.showLoading()
      let data = {
        accountId: this.$store.state.afterSales.userId,
        quotationId: this.detailData.quotationId,
        products: this.productList.map(item => ({
          productId: item.productId,
          productName: item.productName,
          costPrice: item.inPrice,
          rateIncrease: item.addRange,
          count: item.productCount,
          couponId: item.couponId,
          coupon_Details_Id: item.coupon_Details_Id,
          couponMoney: item.couponMoney,
          productTypeId: item.goodsTypeId,
          actuallyAmount: item.actuallyAmount || item.productPrice,
          productPrice: item.productPrice,
        })),
        services: this.serveList.map(item => ({
          serviceTypeId: item.serviceId,
          serviceName: item.serviceName,
          servicePrice: Number(item.servicePrice),
          serviceCount: item.serviceCount,
          couponId: item.couponId,
          coupon_Details_Id: item.coupon_Details_Id,
          couponMoney: item.couponMoney,
          service_Calculate_Rule_id: item.service_Calculate_Rule_id,
        })),
        couponAllMoney: '-' + this.couponAllMoney,
        allMoney: this.priceData.totalPrice,
        otherCoupons: this.otherCoupons,
        reason: this.remark,
        freight: this.freightVal ? parseFloat(this.freightVal) : 0,
      }
      try {
        const res = await this.$api.afterSales.PostQuotation(data)

        this.isSubmit = true
        uni.setNavigationBarTitle({
          title: '报价单-已生成订单',
        })
        this.userConfirm(res.data)
      } catch (err) {
        console.log(err)
      }
      uni.hideLoading()
    },
    //上传收据图片
    choosePic() {
      const _this = this
      uni.showActionSheet({
        itemList: ['拍照', '打开相册'],
        success(res) {
          const cameraType = res.tapIndex ? 'album' : 'camera'
          uni.chooseImage({
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: [cameraType], // 从相册选择
            success: function (result) {
              uni.showLoading({
                title: '图片上传中~',
              })
              _this.$api.files
                .uploadImg({
                  filePath: result.tempFilePaths[0],
                })
                .then(res => {
                  // res.baseUrl + res.url
                  _this.billImg = res.baseUrl + res.url
                  uni.hideLoading()
                })
                .catch(err => {
                  uni.hideLoading()
                  uni.showToast({
                    title: '图片上传失败，请稍后重试',
                    icon: 'none',
                  })
                })
            },
          })
        },
      })
    },

    //现金支付提交
    cashPayments() {
      if (!this.billImg || this.billImg === '/static/img/afterSales/piao.png') {
        uni.showToast({
          title: '请上传收据',
          icon: 'none',
        })
        return
      }

      this.$api.afterSales
        .cashPayments({
          cashReceiptsImg: this.billImg,
          cashReceiptsImg_Note: this.billRemark,
          quotationId: this.detailData.quotationId,
        })
        .then(res => {
          if (res.data) {
            uni.showToast({
              title: '提交成功',
            })
          }
          this.getDetailData()
        })
        .catch(err => {
          console.log(err)
        })
    },
  },
}
